
<!DOCTYPE HTML>
<html lang="" >
    <head>
        <meta charset="UTF-8">
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>线程局部存储 · GitBook</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="GitBook 3.2.2">
        
        
        
    
    <link rel="stylesheet" href="../gitbook/style.css">

    
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-highlight/website.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-search/search.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-fontsettings/website.css">
                
            
        

    

    
        
    
        
    
        
    
        
    
        
    
        
    

        
    
    
    <meta name="HandheldFriendly" content="true"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
    <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">

    
    <link rel="next" href="others.html" />
    
    
    <link rel="prev" href="lock.html" />
    

    </head>
    <body>
        
<div class="book">
    <div class="book-summary">
        
            
<div id="book-search-input" role="search">
    <input type="text" placeholder="Type to search" />
</div>

            
                <nav role="navigation">
                


<ul class="summary">
    
    

    

    
        
        <li class="header">Java</li>
        
        
    
        <li class="chapter " data-level="1.1" data-path="../">
            
                <a href="../">
            
                    
                    Introduction
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="../object-mgmr.html">
            
                <a href="../object-mgmr.html">
            
                    
                    对象管理
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3" data-path="../enum.html">
            
                <a href="../enum.html">
            
                    
                    枚举
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4" data-path="../object-common.html">
            
                <a href="../object-common.html">
            
                    
                    对象通用行为
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5" data-path="../concurrent.html">
            
                <a href="../concurrent.html">
            
                    
                    线程和并发
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.5.1" data-path="how-to.html">
            
                <a href="how-to.html">
            
                    
                    线程和线程池
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.2" data-path="block-close.html">
            
                <a href="block-close.html">
            
                    
                    线程阻塞和关闭
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.3" data-path="communicate.html">
            
                <a href="communicate.html">
            
                    
                    线程协作
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.4" data-path="volatile.html">
            
                <a href="volatile.html">
            
                    
                    活性失败-volatile
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.5" data-path="lock.html">
            
                <a href="lock.html">
            
                    
                    安全性失败-锁
            
                </a>
            

            
        </li>
    
        <li class="chapter active" data-level="1.5.6" data-path="thread-local.html">
            
                <a href="thread-local.html">
            
                    
                    线程局部存储
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.7" data-path="others.html">
            
                <a href="others.html">
            
                    
                    其他
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.6" data-path="../collections.html">
            
                <a href="../collections.html">
            
                    
                    集合
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.7" data-path="../nio.html">
            
                <a href="../nio.html">
            
                    
                    nio
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.8" data-path="../advance.html">
            
                <a href="../advance.html">
            
                    
                    泛型，注解和反射
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9" data-path="../mem-gc.html">
            
                <a href="../mem-gc.html">
            
                    
                    内存模型和GC
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.10" data-path="../classloader.html">
            
                <a href="../classloader.html">
            
                    
                    ClassLoader
            
                </a>
            

            
        </li>
    

    
        
        <li class="header">Web</li>
        
        
    
        <li class="chapter " data-level="2.1" data-path="../spring.html">
            
                <a href="../spring.html">
            
                    
                    spring
            
                </a>
            

            
        </li>
    

    
        
        <li class="header">GUI</li>
        
        
    
        <li class="chapter " data-level="3.1" data-path="../gui-1.html">
            
                <a href="../gui-1.html">
            
                    
                    没事写个小界面什么的
            
                </a>
            

            
        </li>
    

    

    <li class="divider"></li>

    <li>
        <a href="https://www.gitbook.com" target="blank" class="gitbook-link">
            Published with GitBook
        </a>
    </li>
</ul>


                </nav>
            
        
    </div>

    <div class="book-body">
        
            <div class="body-inner">
                
                    

<div class="book-header" role="navigation">
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href=".." >线程局部存储</a>
    </h1>
</div>




                    <div class="page-wrapper" tabindex="-1" role="main">
                        <div class="page-inner">
                            
<div id="book-search-results">
    <div class="search-noresults">
    
                                <section class="normal markdown-section">
                                
                                <h1 id="&#x7EBF;&#x7A0B;&#x5C40;&#x90E8;&#x5B58;&#x50A8;">&#x7EBF;&#x7A0B;&#x5C40;&#x90E8;&#x5B58;&#x50A8;</h1>
<pre><code>public static class ThreadLocalVariableHolder{

    private static ThreadLocal&lt;Integer&gt; value = new ThreadLocal&lt;Integer&gt;(){
        private Random rand = new Random(47);
        protected synchronized Integer initialValue(){
            return rand.nextInt(1000);
        }
    };

    public static void increment(){
        value.set(value.get() + 1);
    }

    public static int get(){
        return value.get();
    }
}
</code></pre><p>&#x867D;&#x7136;&#x53EA;&#x6709;&#x4E00;&#x4E2A;ThreadLocal<integer>   value&#x7684;&#x9759;&#x6001;&#x53D8;&#x91CF;&#xFF0C;&#x800C;&#x4E14;&#x770B;&#x8D77;&#x6765;&#x597D;&#x50CF;&#x53EA;&#x80FD;&#x653E;&#x8FDB;&#x4E00;&#x4E2A;int&#x503C;&#xFF0C;<br>&#x4F46;&#x5B9E;&#x9645;&#x4E0A;&#x6BCF;&#x4E2A;&#x8BBF;&#x95EE;&#x8FD9;&#x4E2A;value&#x5BF9;&#x8C61;&#x7684;&#x7EBF;&#x7A0B;&#xFF0C;&#x90FD;&#x6709;&#x4E86;&#x81EA;&#x5DF1;&#x7684;&#x4E00;&#x4EFD;&#x62F7;&#x8D1D;&#xFF0C;&#x4E92;&#x4E0D;&#x5E72;&#x6270;&#x3002;<br>&#x6240;&#x4EE5;&#x7528;&#x8D77;&#x6765;&#x597D;&#x50CF;&#x662F;&#x4E00;&#x4E2A;Map&#xFF0C;&#x800C;&#x4E14;key&#x662F;&#x7EBF;&#x7A0B;id&#x4E4B;&#x7C7B;&#x7684;   </integer></p>
<hr>
<p>&#x9996;&#x5148;&#xFF0C;ThreadLocal &#x4E0D;&#x662F;&#x7528;&#x6765;&#x89E3;&#x51B3;&#x5171;&#x4EAB;&#x5BF9;&#x8C61;&#x7684;&#x591A;&#x7EBF;&#x7A0B;&#x8BBF;&#x95EE;&#x95EE;&#x9898;&#x7684;&#xFF0C;&#x4E00;&#x822C;&#x60C5;&#x51B5;&#x4E0B;&#xFF0C;&#x901A;&#x8FC7;ThreadLocal.set() &#x5230;&#x7EBF;&#x7A0B;&#x4E2D;&#x7684;&#x5BF9;&#x8C61;&#x662F;&#x8BE5;&#x7EBF;&#x7A0B;&#x81EA;&#x5DF1;&#x4F7F;&#x7528;&#x7684;&#x5BF9;&#x8C61;&#xFF0C;&#x5176;&#x4ED6;&#x7EBF;&#x7A0B;&#x662F;&#x4E0D;&#x9700;&#x8981;&#x8BBF;&#x95EE;&#x7684;&#xFF0C;&#x4E5F;&#x8BBF;&#x95EE;&#x4E0D;&#x5230;&#x7684;&#x3002;&#x5404;&#x4E2A;&#x7EBF;&#x7A0B;&#x4E2D;&#x8BBF;&#x95EE;&#x7684;&#x662F;&#x4E0D;&#x540C;&#x7684;&#x5BF9;&#x8C61;&#x3002; </p>
<p>&#x53E6;&#x5916;&#xFF0C;&#x8BF4;ThreadLocal&#x4F7F;&#x5F97;&#x5404;&#x7EBF;&#x7A0B;&#x80FD;&#x591F;&#x4FDD;&#x6301;&#x5404;&#x81EA;&#x72EC;&#x7ACB;&#x7684;&#x4E00;&#x4E2A;&#x5BF9;&#x8C61;&#xFF0C;&#x5E76;&#x4E0D;&#x662F;&#x901A;&#x8FC7;ThreadLocal.set()&#x6765;&#x5B9E;&#x73B0;&#x7684;&#xFF0C;&#x800C;&#x662F;&#x901A;&#x8FC7;&#x6BCF;&#x4E2A;&#x7EBF;&#x7A0B;&#x4E2D;&#x7684;new &#x5BF9;&#x8C61; &#x7684;&#x64CD;&#x4F5C;&#x6765;&#x521B;&#x5EFA;&#x7684;&#x5BF9;&#x8C61;&#xFF0C;&#x6BCF;&#x4E2A;&#x7EBF;&#x7A0B;&#x521B;&#x5EFA;&#x4E00;&#x4E2A;&#xFF0C;&#x4E0D;&#x662F;&#x4EC0;&#x4E48;&#x5BF9;&#x8C61;&#x7684;&#x62F7;&#x8D1D;&#x6216;&#x526F;&#x672C;&#x3002;&#x901A;&#x8FC7;ThreadLocal.set()&#x5C06;&#x8FD9;&#x4E2A;&#x65B0;&#x521B;&#x5EFA;&#x7684;&#x5BF9;&#x8C61;&#x7684;&#x5F15;&#x7528;&#x4FDD;&#x5B58;&#x5230;&#x5404;&#x7EBF;&#x7A0B;&#x7684;&#x81EA;&#x5DF1;&#x7684;&#x4E00;&#x4E2A;map&#x4E2D;&#xFF0C;&#x6BCF;&#x4E2A;&#x7EBF;&#x7A0B;&#x90FD;&#x6709;&#x8FD9;&#x6837;&#x4E00;&#x4E2A;map&#xFF0C;&#x6267;&#x884C;ThreadLocal.get()&#x65F6;&#xFF0C;&#x5404;&#x7EBF;&#x7A0B;&#x4ECE;&#x81EA;&#x5DF1;&#x7684;map&#x4E2D;&#x53D6;&#x51FA;&#x653E;&#x8FDB;&#x53BB;&#x7684;&#x5BF9;&#x8C61;&#xFF0C;&#x56E0;&#x6B64;&#x53D6;&#x51FA;&#x6765;&#x7684;&#x662F;&#x5404;&#x81EA;&#x81EA;&#x5DF1;&#x7EBF;&#x7A0B;&#x4E2D;&#x7684;&#x5BF9;&#x8C61;&#xFF0C;ThreadLocal&#x5B9E;&#x4F8B;&#x662F;&#x4F5C;&#x4E3A;map&#x7684;key&#x6765;&#x4F7F;&#x7528;&#x7684;&#x3002; </p>
<p>&#x5982;&#x679C;ThreadLocal.set()&#x8FDB;&#x53BB;&#x7684;&#x4E1C;&#x897F;&#x672C;&#x6765;&#x5C31;&#x662F;&#x591A;&#x4E2A;&#x7EBF;&#x7A0B;&#x5171;&#x4EAB;&#x7684;&#x540C;&#x4E00;&#x4E2A;&#x5BF9;&#x8C61;&#xFF0C;&#x90A3;&#x4E48;&#x591A;&#x4E2A;&#x7EBF;&#x7A0B;&#x7684;ThreadLocal.get()&#x53D6;&#x5F97;&#x7684;&#x8FD8;&#x662F;&#x8FD9;&#x4E2A;&#x5171;&#x4EAB;&#x5BF9;&#x8C61;&#x672C;&#x8EAB;&#xFF0C;&#x8FD8;&#x662F;&#x6709;&#x5E76;&#x53D1;&#x8BBF;&#x95EE;&#x95EE;&#x9898;&#x3002; </p>
<p>&#x4E0B;&#x9762;&#x6765;&#x770B;&#x4E00;&#x4E2A;hibernate&#x4E2D;&#x5178;&#x578B;&#x7684;ThreadLocal&#x7684;&#x5E94;&#x7528;&#xFF1A; </p>
<pre><code>private static final ThreadLocal threadSession = new ThreadLocal();  

public static Session getSession() throws InfrastructureException {  
    Session s = (Session) threadSession.get();  
    try {  
        if (s == null) {  
            s = getSessionFactory().openSession();  
            threadSession.set(s);  
        }  
    } catch (HibernateException ex) {  
        throw new InfrastructureException(ex);  
    }  
    return s;  
}
</code></pre><p>&#x53EF;&#x4EE5;&#x770B;&#x5230;&#x5728;getSession()&#x65B9;&#x6CD5;&#x4E2D;&#xFF0C;&#x9996;&#x5148;&#x5224;&#x65AD;&#x5F53;&#x524D;&#x7EBF;&#x7A0B;&#x4E2D;&#x6709;&#x6CA1;&#x6709;&#x653E;&#x8FDB;&#x53BB;session&#xFF0C;&#x5982;&#x679C;&#x8FD8;&#x6CA1;&#x6709;&#xFF0C;&#x90A3;&#x4E48;&#x901A;&#x8FC7;sessionFactory().openSession()&#x6765;&#x521B;&#x5EFA;&#x4E00;&#x4E2A;session&#xFF0C;&#x518D;&#x5C06;session set&#x5230;&#x7EBF;&#x7A0B;&#x4E2D;&#xFF0C;&#x5B9E;&#x9645;&#x662F;&#x653E;&#x5230;&#x5F53;&#x524D;&#x7EBF;&#x7A0B;&#x7684;ThreadLocalMap&#x8FD9;&#x4E2A;map&#x4E2D;&#xFF0C;&#x8FD9;&#x65F6;&#xFF0C;&#x5BF9;&#x4E8E;&#x8FD9;&#x4E2A;session&#x7684;&#x552F;&#x4E00;&#x5F15;&#x7528;&#x5C31;&#x662F;&#x5F53;&#x524D;&#x7EBF;&#x7A0B;&#x4E2D;&#x7684;&#x90A3;&#x4E2A;ThreadLocalMap&#xFF08;&#x4E0B;&#x9762;&#x4F1A;&#x8BB2;&#x5230;&#xFF09;&#xFF0C;&#x800C;threadSession&#x4F5C;&#x4E3A;&#x8FD9;&#x4E2A;&#x503C;&#x7684;key&#xFF0C;&#x8981;&#x53D6;&#x5F97;&#x8FD9;&#x4E2A;session&#x53EF;&#x4EE5;&#x901A;&#x8FC7;threadSession.get()&#x6765;&#x5F97;&#x5230;&#xFF0C;&#x91CC;&#x9762;&#x6267;&#x884C;&#x7684;&#x64CD;&#x4F5C;&#x5B9E;&#x9645;&#x662F;&#x5148;&#x53D6;&#x5F97;&#x5F53;&#x524D;&#x7EBF;&#x7A0B;&#x4E2D;&#x7684;ThreadLocalMap&#xFF0C;&#x7136;&#x540E;&#x5C06;threadSession&#x4F5C;&#x4E3A;key&#x5C06;&#x5BF9;&#x5E94;&#x7684;&#x503C;&#x53D6;&#x51FA;&#x3002;&#x8FD9;&#x4E2A;session&#x76F8;&#x5F53;&#x4E8E;&#x7EBF;&#x7A0B;&#x7684;&#x79C1;&#x6709;&#x53D8;&#x91CF;&#xFF0C;&#x800C;&#x4E0D;&#x662F;public&#x7684;&#x3002; 
&#x663E;&#x7136;&#xFF0C;&#x5176;&#x4ED6;&#x7EBF;&#x7A0B;&#x4E2D;&#x662F;&#x53D6;&#x4E0D;&#x5230;&#x8FD9;&#x4E2A;session&#x7684;&#xFF0C;&#x4ED6;&#x4EEC;&#x4E5F;&#x53EA;&#x80FD;&#x53D6;&#x5230;&#x81EA;&#x5DF1;&#x7684;ThreadLocalMap&#x4E2D;&#x7684;&#x4E1C;&#x897F;&#x3002;&#x8981;&#x662F;session&#x662F;&#x591A;&#x4E2A;&#x7EBF;&#x7A0B;&#x5171;&#x4EAB;&#x4F7F;&#x7528;&#x7684;&#xFF0C;&#x90A3;&#x8FD8;&#x4E0D;&#x4E71;&#x5957;&#x4E86;&#x3002; 
&#x8BD5;&#x60F3;&#x5982;&#x679C;&#x4E0D;&#x7528;ThreadLocal&#x600E;&#x4E48;&#x6765;&#x5B9E;&#x73B0;&#x5462;&#xFF1F;&#x53EF;&#x80FD;&#x5C31;&#x8981;&#x5728;action&#x4E2D;&#x521B;&#x5EFA;session&#xFF0C;&#x7136;&#x540E;&#x628A;session&#x4E00;&#x4E2A;&#x4E2A;&#x4F20;&#x5230;service&#x548C;dao&#x4E2D;&#xFF0C;&#x8FD9;&#x53EF;&#x591F;&#x9EBB;&#x70E6;&#x7684;&#x3002;&#x6216;&#x8005;&#x53EF;&#x4EE5;&#x81EA;&#x5DF1;&#x5B9A;&#x4E49;&#x4E00;&#x4E2A;&#x9759;&#x6001;&#x7684;map&#xFF0C;&#x5C06;&#x5F53;&#x524D;thread&#x4F5C;&#x4E3A;key&#xFF0C;&#x521B;&#x5EFA;&#x7684;session&#x4F5C;&#x4E3A;&#x503C;&#xFF0C;put&#x5230;map&#x4E2D;&#xFF0C;&#x5E94;&#x8BE5;&#x4E5F;&#x884C;&#xFF0C;&#x8FD9;&#x4E5F;&#x662F;&#x4E00;&#x822C;&#x4EBA;&#x7684;&#x60F3;&#x6CD5;&#xFF0C;&#x4F46;&#x4E8B;&#x5B9E;&#x4E0A;&#xFF0C;ThreadLocal&#x7684;&#x5B9E;&#x73B0;&#x521A;&#x597D;&#x76F8;&#x53CD;&#xFF0C;&#x5B83;&#x662F;&#x5728;&#x6BCF;&#x4E2A;&#x7EBF;&#x7A0B;&#x4E2D;&#x6709;&#x4E00;&#x4E2A;map&#xFF0C;&#x800C;&#x5C06;ThreadLocal&#x5B9E;&#x4F8B;&#x4F5C;&#x4E3A;key&#xFF0C;&#x8FD9;&#x6837;&#x6BCF;&#x4E2A;map&#x4E2D;&#x7684;&#x9879;&#x6570;&#x5F88;&#x5C11;&#xFF0C;&#x800C;&#x4E14;&#x5F53;&#x7EBF;&#x7A0B;&#x9500;&#x6BC1;&#x65F6;&#x76F8;&#x5E94;&#x7684;&#x4E1C;&#x897F;&#x4E5F;&#x4E00;&#x8D77;&#x9500;&#x6BC1;&#x4E86;&#xFF0C;&#x4E0D;&#x77E5;&#x9053;&#x9664;&#x4E86;&#x8FD9;&#x4E9B;&#x8FD8;&#x6709;&#x4EC0;&#x4E48;&#x5176;&#x4ED6;&#x7684;&#x597D;&#x5904;&#x3002; </p>
<p>&#x603B;&#x4E4B;&#xFF0C;ThreadLocal&#x4E0D;&#x662F;&#x7528;&#x6765;&#x89E3;&#x51B3;&#x5BF9;&#x8C61;&#x5171;&#x4EAB;&#x8BBF;&#x95EE;&#x95EE;&#x9898;&#x7684;&#xFF0C;&#x800C;&#x4E3B;&#x8981;&#x662F;&#x63D0;&#x4F9B;&#x4E86;&#x4FDD;&#x6301;&#x5BF9;&#x8C61;&#x7684;&#x65B9;&#x6CD5;&#x548C;&#x907F;&#x514D;&#x53C2;&#x6570;&#x4F20;&#x9012;&#x7684;&#x65B9;&#x4FBF;&#x7684;&#x5BF9;&#x8C61;&#x8BBF;&#x95EE;&#x65B9;&#x5F0F;&#x3002;&#x5F52;&#x7EB3;&#x4E86;&#x4E24;&#x70B9;&#xFF1A; 
1&#x3002;&#x6BCF;&#x4E2A;&#x7EBF;&#x7A0B;&#x4E2D;&#x90FD;&#x6709;&#x4E00;&#x4E2A;&#x81EA;&#x5DF1;&#x7684;ThreadLocalMap&#x7C7B;&#x5BF9;&#x8C61;&#xFF0C;&#x53EF;&#x4EE5;&#x5C06;&#x7EBF;&#x7A0B;&#x81EA;&#x5DF1;&#x7684;&#x5BF9;&#x8C61;&#x4FDD;&#x6301;&#x5230;&#x5176;&#x4E2D;&#xFF0C;&#x5404;&#x7BA1;&#x5404;&#x7684;&#xFF0C;&#x7EBF;&#x7A0B;&#x53EF;&#x4EE5;&#x6B63;&#x786E;&#x7684;&#x8BBF;&#x95EE;&#x5230;&#x81EA;&#x5DF1;&#x7684;&#x5BF9;&#x8C61;&#x3002; 
2&#x3002;&#x5C06;&#x4E00;&#x4E2A;&#x5171;&#x7528;&#x7684;ThreadLocal&#x9759;&#x6001;&#x5B9E;&#x4F8B;&#x4F5C;&#x4E3A;key&#xFF0C;&#x5C06;&#x4E0D;&#x540C;&#x5BF9;&#x8C61;&#x7684;&#x5F15;&#x7528;&#x4FDD;&#x5B58;&#x5230;&#x4E0D;&#x540C;&#x7EBF;&#x7A0B;&#x7684;ThreadLocalMap&#x4E2D;&#xFF0C;&#x7136;&#x540E;&#x5728;&#x7EBF;&#x7A0B;&#x6267;&#x884C;&#x7684;&#x5404;&#x5904;&#x901A;&#x8FC7;&#x8FD9;&#x4E2A;&#x9759;&#x6001;ThreadLocal&#x5B9E;&#x4F8B;&#x7684;get()&#x65B9;&#x6CD5;&#x53D6;&#x5F97;&#x81EA;&#x5DF1;&#x7EBF;&#x7A0B;&#x4FDD;&#x5B58;&#x7684;&#x90A3;&#x4E2A;&#x5BF9;&#x8C61;&#xFF0C;&#x907F;&#x514D;&#x4E86;&#x5C06;&#x8FD9;&#x4E2A;&#x5BF9;&#x8C61;&#x4F5C;&#x4E3A;&#x53C2;&#x6570;&#x4F20;&#x9012;&#x7684;&#x9EBB;&#x70E6;&#x3002; </p>
<p>&#x5F53;&#x7136;&#x5982;&#x679C;&#x8981;&#x628A;&#x672C;&#x6765;&#x7EBF;&#x7A0B;&#x5171;&#x4EAB;&#x7684;&#x5BF9;&#x8C61;&#x901A;&#x8FC7;ThreadLocal.set()&#x653E;&#x5230;&#x7EBF;&#x7A0B;&#x4E2D;&#x4E5F;&#x53EF;&#x4EE5;&#xFF0C;&#x53EF;&#x4EE5;&#x5B9E;&#x73B0;&#x907F;&#x514D;&#x53C2;&#x6570;&#x4F20;&#x9012;&#x7684;&#x8BBF;&#x95EE;&#x65B9;&#x5F0F;&#xFF0C;&#x4F46;&#x662F;&#x8981;&#x6CE8;&#x610F;get()&#x5230;&#x7684;&#x662F;&#x90A3;&#x540C;&#x4E00;&#x4E2A;&#x5171;&#x4EAB;&#x5BF9;&#x8C61;&#xFF0C;&#x5E76;&#x53D1;&#x8BBF;&#x95EE;&#x95EE;&#x9898;&#x8981;&#x9760;&#x5176;&#x4ED6;&#x624B;&#x6BB5;&#x6765;&#x89E3;&#x51B3;&#x3002;&#x4F46;&#x4E00;&#x822C;&#x6765;&#x8BF4;&#x7EBF;&#x7A0B;&#x5171;&#x4EAB;&#x7684;&#x5BF9;&#x8C61;&#x901A;&#x8FC7;&#x8BBE;&#x7F6E;&#x4E3A;&#x67D0;&#x7C7B;&#x7684;&#x9759;&#x6001;&#x53D8;&#x91CF;&#x5C31;&#x53EF;&#x4EE5;&#x5B9E;&#x73B0;&#x65B9;&#x4FBF;&#x7684;&#x8BBF;&#x95EE;&#x4E86;&#xFF0C;&#x4F3C;&#x4E4E;&#x6CA1;&#x5FC5;&#x8981;&#x653E;&#x5230;&#x7EBF;&#x7A0B;&#x4E2D;&#x3002; </p>
<p>ThreadLocal&#x7684;&#x5E94;&#x7528;&#x573A;&#x5408;&#xFF0C;&#x6211;&#x89C9;&#x5F97;&#x6700;&#x9002;&#x5408;&#x7684;&#x662F;&#x6309;&#x7EBF;&#x7A0B;&#x591A;&#x5B9E;&#x4F8B;&#xFF08;&#x6BCF;&#x4E2A;&#x7EBF;&#x7A0B;&#x5BF9;&#x5E94;&#x4E00;&#x4E2A;&#x5B9E;&#x4F8B;&#xFF09;&#x7684;&#x5BF9;&#x8C61;&#x7684;&#x8BBF;&#x95EE;&#xFF0C;&#x5E76;&#x4E14;&#x8FD9;&#x4E2A;&#x5BF9;&#x8C61;&#x5F88;&#x591A;&#x5730;&#x65B9;&#x90FD;&#x8981;&#x7528;&#x5230;&#x3002; </p>
<p>&#x4E0B;&#x9762;&#x6765;&#x770B;&#x770B;ThreadLocal&#x7684;&#x5B9E;&#x73B0;&#x539F;&#x7406;&#xFF08;jdk1.5&#x6E90;&#x7801;&#xFF09; </p>
<pre><code>public class ThreadLocal&lt;T&gt; {  
    /** 
     * ThreadLocals rely on per-thread hash maps attached to each thread 
     * (Thread.threadLocals and inheritableThreadLocals).  The ThreadLocal 
     * objects act as keys, searched via threadLocalHashCode.  This is a 
     * custom hash code (useful only within ThreadLocalMaps) that eliminates 
     * collisions in the common case where consecutively constructed 
     * ThreadLocals are used by the same threads, while remaining well-behaved 
     * in less common cases. 
     */  
    private final int threadLocalHashCode = nextHashCode();  

    /** 
     * The next hash code to be given out. Accessed only by like-named method. 
     */  
    private static int nextHashCode = 0;  

    /** 
     * The difference between successively generated hash codes - turns 
     * implicit sequential thread-local IDs into near-optimally spread 
     * multiplicative hash values for power-of-two-sized tables. 
     */  
    private static final int HASH_INCREMENT = 0x61c88647;  

    /** 
     * Compute the next hash code. The static synchronization used here 
     * should not be a performance bottleneck. When ThreadLocals are 
     * generated in different threads at a fast enough rate to regularly 
     * contend on this lock, memory contention is by far a more serious 
     * problem than lock contention. 
     */  
    private static synchronized int nextHashCode() {  
        int h = nextHashCode;  
        nextHashCode = h + HASH_INCREMENT;  
        return h;  
    }  

    /** 
     * Creates a thread local variable. 
     */  
    public ThreadLocal() {  
    }  

    /** 
     * Returns the value in the current thread&apos;s copy of this thread-local 
     * variable.  Creates and initializes the copy if this is the first time 
     * the thread has called this method. 
     * 
     * @return the current thread&apos;s value of this thread-local 
     */  
    public T get() {  
        Thread t = Thread.currentThread();  
        ThreadLocalMap map = getMap(t);  
        if (map != null)  
            return (T)map.get(this);  

        // Maps are constructed lazily.  if the map for this thread  
        // doesn&apos;t exist, create it, with this ThreadLocal and its  
        // initial value as its only entry.  
        T value = initialValue();  
        createMap(t, value);  
        return value;  
    }  

    /** 
     * Sets the current thread&apos;s copy of this thread-local variable 
     * to the specified value.  Many applications will have no need for 
     * this functionality, relying solely on the {@link #initialValue} 
     * method to set the values of thread-locals. 
     * 
     * @param value the value to be stored in the current threads&apos; copy of 
     *        this thread-local. 
     */  
    public void set(T value) {  
        Thread t = Thread.currentThread();  
        ThreadLocalMap map = getMap(t);  
        if (map != null)  
            map.set(this, value);  
        else  
            createMap(t, value);  
    }  

    /** 
     * Get the map associated with a ThreadLocal. Overridden in 
     * InheritableThreadLocal. 
     * 
     * @param  t the current thread 
     * @return the map 
     */  
    ThreadLocalMap getMap(Thread t) {  
        return t.threadLocals;  
    }  

    /** 
     * Create the map associated with a ThreadLocal. Overridden in 
     * InheritableThreadLocal. 
     * 
     * @param t the current thread 
     * @param firstValue value for the initial entry of the map 
     * @param map the map to store. 
     */  
    void createMap(Thread t, T firstValue) {  
        t.threadLocals = new ThreadLocalMap(this, firstValue);  
    }  

    .......  

    /** 
     * ThreadLocalMap is a customized hash map suitable only for 
     * maintaining thread local values. No operations are exported 
     * outside of the ThreadLocal class. The class is package private to 
     * allow declaration of fields in class Thread.  To help deal with 
     * very large and long-lived usages, the hash table entries use 
     * WeakReferences for keys. However, since reference queues are not 
     * used, stale entries are guaranteed to be removed only when 
     * the table starts running out of space. 
     */  
    static class ThreadLocalMap {  

    ........  

    }  

}
</code></pre><p>&#x53EF;&#x4EE5;&#x770B;&#x5230;ThreadLocal&#x7C7B;&#x4E2D;&#x7684;&#x53D8;&#x91CF;&#x53EA;&#x6709;&#x8FD9;3&#x4E2A;int&#x578B;&#xFF1A; </p>
<pre><code>private final int threadLocalHashCode = nextHashCode();  
private static int nextHashCode = 0;  
private static final int HASH_INCREMENT = 0x61c88647;
</code></pre><p>&#x800C;&#x4F5C;&#x4E3A;ThreadLocal&#x5B9E;&#x4F8B;&#x7684;&#x53D8;&#x91CF;&#x53EA;&#x6709; threadLocalHashCode &#x8FD9;&#x4E00;&#x4E2A;&#xFF0C;nextHashCode &#x548C;HASH_INCREMENT &#x662F;ThreadLocal&#x7C7B;&#x7684;&#x9759;&#x6001;&#x53D8;&#x91CF;&#xFF0C;&#x5B9E;&#x9645;&#x4E0A;HASH_INCREMENT&#x662F;&#x4E00;&#x4E2A;&#x5E38;&#x91CF;&#xFF0C;&#x8868;&#x793A;&#x4E86;&#x8FDE;&#x7EED;&#x5206;&#x914D;&#x7684;&#x4E24;&#x4E2A;ThreadLocal&#x5B9E;&#x4F8B;&#x7684;threadLocalHashCode&#x503C;&#x7684;&#x589E;&#x91CF;&#xFF0C;&#x800C;nextHashCode &#x7684;&#x8868;&#x793A;&#x4E86;&#x5373;&#x5C06;&#x5206;&#x914D;&#x7684;&#x4E0B;&#x4E00;&#x4E2A;ThreadLocal&#x5B9E;&#x4F8B;&#x7684;threadLocalHashCode &#x7684;&#x503C;&#x3002; </p>
<p>&#x53EF;&#x4EE5;&#x6765;&#x770B;&#x4E00;&#x4E0B;&#x521B;&#x5EFA;&#x4E00;&#x4E2A;ThreadLocal&#x5B9E;&#x4F8B;&#x5373;new ThreadLocal()&#x65F6;&#x505A;&#x4E86;&#x54EA;&#x4E9B;&#x64CD;&#x4F5C;&#xFF0C;&#x4ECE;&#x4E0A;&#x9762;&#x770B;&#x5230;&#x6784;&#x9020;&#x51FD;&#x6570;ThreadLocal()&#x91CC;&#x4EC0;&#x4E48;&#x64CD;&#x4F5C;&#x90FD;&#x6CA1;&#x6709;&#xFF0C;&#x552F;&#x4E00;&#x7684;&#x64CD;&#x4F5C;&#x662F;&#x8FD9;&#x53E5;&#xFF1A; </p>
<pre><code>private final int threadLocalHashCode = nextHashCode();
</code></pre><p>&#x90A3;&#x4E48;nextHashCode()&#x505A;&#x4E86;&#x4EC0;&#x4E48;&#x5462;&#xFF1A; </p>
<pre><code>private static synchronized int nextHashCode() {  
    int h = nextHashCode;  
    nextHashCode = h + HASH_INCREMENT;  
    return h;  
}
</code></pre><p>&#x5C31;&#x662F;&#x5C06;ThreadLocal&#x7C7B;&#x7684;&#x4E0B;&#x4E00;&#x4E2A;hashCode&#x503C;&#x5373;nextHashCode&#x7684;&#x503C;&#x8D4B;&#x7ED9;&#x5B9E;&#x4F8B;&#x7684;threadLocalHashCode&#xFF0C;&#x7136;&#x540E;nextHashCode&#x7684;&#x503C;&#x589E;&#x52A0;HASH_INCREMENT&#x8FD9;&#x4E2A;&#x503C;&#x3002; </p>
<p>&#x56E0;&#x6B64;ThreadLocal&#x5B9E;&#x4F8B;&#x7684;&#x53D8;&#x91CF;&#x53EA;&#x6709;&#x8FD9;&#x4E2A;threadLocalHashCode&#xFF0C;&#x800C;&#x4E14;&#x662F;final&#x7684;&#xFF0C;&#x7528;&#x6765;&#x533A;&#x5206;&#x4E0D;&#x540C;&#x7684;ThreadLocal&#x5B9E;&#x4F8B;&#xFF0C;ThreadLocal&#x7C7B;&#x4E3B;&#x8981;&#x662F;&#x4F5C;&#x4E3A;&#x5DE5;&#x5177;&#x7C7B;&#x6765;&#x4F7F;&#x7528;&#xFF0C;&#x90A3;&#x4E48;ThreadLocal.set()&#x8FDB;&#x53BB;&#x7684;&#x5BF9;&#x8C61;&#x662F;&#x653E;&#x5728;&#x54EA;&#x513F;&#x7684;&#x5462;&#xFF1F; </p>
<p>&#x770B;&#x4E00;&#x4E0B;&#x4E0A;&#x9762;&#x7684;set()&#x65B9;&#x6CD5;&#xFF0C;&#x4E24;&#x53E5;&#x5408;&#x5E76;&#x4E00;&#x4E0B;&#x6210;&#x4E3A; </p>
<pre><code>ThreadLocalMap map = Thread.currentThread().threadLocals;
</code></pre><p>&#x8FD9;&#x4E2A;ThreadLocalMap &#x7C7B;&#x662F;ThreadLocal&#x4E2D;&#x5B9A;&#x4E49;&#x7684;&#x5185;&#x90E8;&#x7C7B;&#xFF0C;&#x4F46;&#x662F;&#x5B83;&#x7684;&#x5B9E;&#x4F8B;&#x5374;&#x7528;&#x5728;Thread&#x7C7B;&#x4E2D;&#xFF1A; </p>
<pre><code>public class Thread implements Runnable {  
    ......  

    /* ThreadLocal values pertaining to this thread. This map is maintained 
     * by the ThreadLocal class. */  
    ThreadLocal.ThreadLocalMap threadLocals = null;    
    ......  
}
</code></pre><p>&#x518D;&#x770B;&#x8FD9;&#x53E5;&#xFF1A; </p>
<pre><code>if (map != null)  
    map.set(this, value);
</code></pre><p>&#x4E5F;&#x5C31;&#x662F;&#x5C06;&#x8BE5;ThreadLocal&#x5B9E;&#x4F8B;&#x4F5C;&#x4E3A;key&#xFF0C;&#x8981;&#x4FDD;&#x6301;&#x7684;&#x5BF9;&#x8C61;&#x4F5C;&#x4E3A;&#x503C;&#xFF0C;&#x8BBE;&#x7F6E;&#x5230;&#x5F53;&#x524D;&#x7EBF;&#x7A0B;&#x7684;ThreadLocalMap &#x4E2D;&#xFF0C;get()&#x65B9;&#x6CD5;&#x540C;&#x6837;&#x5927;&#x5BB6;&#x770B;&#x4E86;&#x4EE3;&#x7801;&#x4E5F;&#x5C31;&#x660E;&#x767D;&#x4E86;&#x3002;</p>

                                
                                </section>
                            
    </div>
    <div class="search-results">
        <div class="has-results">
            
            <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
            <ul class="search-results-list"></ul>
            
        </div>
        <div class="no-results">
            
            <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
            
        </div>
    </div>
</div>

                        </div>
                    </div>
                
            </div>

            
                
                <a href="lock.html" class="navigation navigation-prev " aria-label="Previous page: 安全性失败-锁">
                    <i class="fa fa-angle-left"></i>
                </a>
                
                
                <a href="others.html" class="navigation navigation-next " aria-label="Next page: 其他">
                    <i class="fa fa-angle-right"></i>
                </a>
                
            
        
    </div>

    <script>
        var gitbook = gitbook || [];
        gitbook.push(function() {
            gitbook.page.hasChanged({"page":{"title":"线程局部存储","level":"1.5.6","depth":2,"next":{"title":"其他","level":"1.5.7","depth":2,"path":"concurrent/others.md","ref":"concurrent/others.md","articles":[]},"previous":{"title":"安全性失败-锁","level":"1.5.5","depth":2,"path":"concurrent/lock.md","ref":"concurrent/lock.md","articles":[]},"dir":"ltr"},"config":{"gitbook":"*","theme":"default","variables":{},"plugins":[],"pluginsConfig":{"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"}},"file":{"path":"concurrent/thread-local.md","mtime":"2017-04-09T06:00:48.032Z","type":"markdown"},"gitbook":{"version":"3.2.2","time":"2017-04-09T09:50:22.406Z"},"basePath":"..","book":{"language":""}});
        });
    </script>
</div>

        
    <script src="../gitbook/gitbook.js"></script>
    <script src="../gitbook/theme.js"></script>
    
        
        <script src="../gitbook/gitbook-plugin-search/search-engine.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-sharing/buttons.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
        
    

    </body>
</html>

